package com.fuyao.cloud.common.biz.dto;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Setter
public class PageQuery<T> {

    private final static String[] KEYWORDS = {"master", "truncate", "insert", "select", "delete", "update", "declare",
            "alter", "drop", "sleep", "extractvalue", "concat"};

    @JsonProperty("page")
    private PageParam pageParams;
    @Getter
    private T example;

    public Page<T> getPage() {
        Page<T> page = new Page<>();

        Set<String> ascs = pageParams.getAscs();
        Set<String> descs = pageParams.getDescs();
        Long current = pageParams.getCurrent();
        Long size = pageParams.getSize();

        Optional.ofNullable(current).ifPresent(page::setCurrent);
        Optional.ofNullable(size).ifPresent(page::setSize);

        List<OrderItem> orderItems = new ArrayList<>();
        Optional.ofNullable(ascs).ifPresent(s -> orderItems.addAll(ascs.stream().filter(sqlInjectPredicate()).map(s1 -> OrderItem.asc(StrUtil.toUnderlineCase(s1))).collect(Collectors.toList())));
        Optional.ofNullable(descs).ifPresent(s -> orderItems.addAll(descs.stream().filter(sqlInjectPredicate()).map(s1 -> OrderItem.desc(StrUtil.toUnderlineCase(s1))).collect(Collectors.toList())));
        page.addOrder(orderItems);

        return page;
    }

    @Data
    private static class PageParam {
        private Set<String> ascs;
        private Set<String> descs;
        private Long current;
        private Long size;
    }


    /**
     * 判断用户输入里面有没有关键字
     *
     * @return Predicate
     */
    private Predicate<String> sqlInjectPredicate() {
        return sql -> Arrays.stream(KEYWORDS).noneMatch(keyword -> StrUtil.containsIgnoreCase(sql, keyword));
    }
}
